//
//  TDSearchStoreC.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/5.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDSearchStoreC.h"

#import "IANActivityIndicatorButton.h"
#import "UIButton+IANActivityView.h"

#import "TDSearchStoreLeftCell.h"
#import "TDSearchStoreRightCell.h"
#import "TDSearchStoreHeadView.h"
#import "NetWorkRequest.h"
#import "TDCarSourceModel.h"
@interface TDSearchStoreC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;
//@property (nonatomic,strong)NSArray *storeAddressTitleArray;//总共的区的数组

@property (nonatomic,strong)NSMutableArray *totalArray;//所有的数组
@property (nonatomic,strong)NSArray *storeDetailArray;//每个区的---默认进来的话这个数组等于附近门店数组-------
@property (nonatomic,strong)NSArray *originNearStoreArray;//附近门店数组------

@property (nonatomic,strong)IANActivityIndicatorButton *btn_showResult;

@property (nonatomic,copy)NSString *totalCarNum;

@property (weak, nonatomic) IBOutlet UIView *view_showResult;

@end

@implementation TDSearchStoreC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)setupUI {
    //设置导航条
    [self setupNavItem];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.tableFooterView = [UIView new];
    [self.leftTableView registerNib:[UINib nibWithNibName:@"TDSearchStoreLeftCell" bundle:nil] forCellReuseIdentifier:@"TDSearchStoreLeftCellId"];
    self.leftTableView.rowHeight = 55;
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    self.rightTableView.tableFooterView = [UIView new];
    [self.rightTableView registerNib:[UINib nibWithNibName:@"TDSearchStoreRightCell" bundle:nil] forCellReuseIdentifier:@"TDSearchStoreRightCellId"];
    self.rightTableView.rowHeight = 91;
    if ([self.rightTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.rightTableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, -10)];
    }
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setBtnShow];
}



- (void)setupNavItem {
    self.titleText = @"乘车人信息";
}

#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.leftTableView) {
        return self.totalArray.count;
    }
    return self.storeDetailArray.count;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getIdentifier:indexPath tableView:tableView] forIndexPath:indexPath];
    [self setupCell:cell indexPath:indexPath tableView:tableView];
    return cell;
}

- (NSString *)getIdentifier:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    NSString *iden = @"TDSearchStoreLeftCellId";
    if (tableView == self.leftTableView) {
        iden = @"TDSearchStoreLeftCellId";
    }else {
        iden = @"TDSearchStoreRightCellId";
    }
    return iden;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.leftTableView) {
        if (_selLeftIndexPath == indexPath) {
            return;
        }
        // MARK: - 这个可以用选中的来做   不用循环  后续you'hu
        for (TDSearchStoreAreaModel *model in self.totalArray) {
            model.isSel = NO;
            for (TDSearchStoreModel *tmpStoreModel in model.storelist) {
                tmpStoreModel.isSel = NO;
            }
        }
        [self setDefaultBtnShow];
        TDSearchStoreAreaModel *model = self.totalArray[indexPath.row];
        NSArray *tmpArray = model.storelist;
        self.storeDetailArray = tmpArray;//更改右侧数据源--------
        model.isSel = YES;
        self.selLeftIndexPath = indexPath;
        self.selRightIndexPath = nil;
        self.selStoreModel.districtid = model.districtid;
        self.selStoreModel.districtnm = model.districtnm;
        self.selStoreModel.searchStoreModel = nil;
//        [self setLeftHeadView];
        [self.leftTableView reloadData];
        [self.rightTableView reloadData];
        
    }else {
        if (indexPath == _selRightIndexPath) {
            return;
        }
        // MARK: - 这里不要做点击想同indexPath的判断------因为数据源已经完全改变了----------
        for (TDSearchStoreAreaModel *model in self.totalArray) {
            model.isSel = NO;
            for (TDSearchStoreModel *tmpStoreModel in model.storelist) {
                tmpStoreModel.isSel = NO;
            }
        }
        TDSearchStoreModel *tmpStoreModel = self.storeDetailArray[indexPath.row];
        tmpStoreModel.isSel = YES;
        [self.rightTableView reloadData];
        self.selRightIndexPath = indexPath;
        self.selStoreModel.searchStoreModel = tmpStoreModel;
        [self loadAllCarSourceListNetData];
    }
}

- (void)setupCell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (tableView == self.leftTableView) {
        TDSearchStoreLeftCell *searchStoreLeftCell = (TDSearchStoreLeftCell *)cell;
        TDSearchStoreAreaModel *areaModel = self.totalArray[indexPath.row];
        if (areaModel.isSel) {
            searchStoreLeftCell.contentView.backgroundColor = [UIColor whiteColor];
        }else {
            searchStoreLeftCell.contentView.backgroundColor = [UIColor colorWithHex:0xe6e6e6];
        }
        searchStoreLeftCell.lbe_addressTitle.text = areaModel.districtnm;
    }else {
        TDSearchStoreRightCell *searchStoreRightCell = (TDSearchStoreRightCell *)cell;
        TDSearchStoreModel *storeModel = self.storeDetailArray[indexPath.row];
        if (storeModel.isSel) {
            searchStoreRightCell.lbe_storename.textColor = [UIColor colorWithHex:0xbf0021];
            searchStoreRightCell.lbe_address.textColor = [UIColor colorWithHex:0xbf0021];
            searchStoreRightCell.lbe_distance.textColor = [UIColor colorWithHex:0xbf0021];
        }else {
            searchStoreRightCell.lbe_storename.textColor = [UIColor blackColor];
            searchStoreRightCell.lbe_address.textColor = [UIColor blackColor];
            searchStoreRightCell.lbe_distance.textColor = [UIColor blackColor];
        }
        if (self.selLeftIndexPath.row == 0) {
            searchStoreRightCell.lbe_distance.hidden = NO;
        }else {
            searchStoreRightCell.lbe_distance.hidden = YES;
        }
        searchStoreRightCell.lbe_address.text = storeModel.address;
        searchStoreRightCell.lbe_storename.text = storeModel.storename;
    }
}




- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == self.rightTableView) {
        TDSearchStoreHeadView *headView = [TDSearchStoreHeadView searchStoreHeadView];
        if (!self.selLeftIndexPath) {
            headView.lbe_areaTitle.text = @"附近门店";
        }else {
            TDSearchStoreAreaModel *searchStoreAreaModel = self.totalArray[self.selLeftIndexPath.row];
            headView.lbe_areaTitle.text = searchStoreAreaModel.districtnm;
        }
        return headView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.rightTableView) {
        return 50;
    }
    return 0.01;
}



// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
    self.selLeftIndexPath = nil;
    self.selRightIndexPath = nil;
    [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelStoreModel = [TDSearchStoreSelModel new];
    self.selStoreModel = [TDSearchStoreSelModel new];
}

// MARK: - 获取网络数据-----
- (void)loadNetData {
    NSString *topcompanyid = [AppSetting shareAppSetting].topcompanyid;
    NSDictionary *parDic = @{@"topcompanyid":topcompanyid,
                             @"longitude":_locationModel.longitude,
                             @"latitude":_locationModel.latitude
                             };
    __weak typeof(self) weakSelf = self;
    // MARK: - 获取附近位置的网络数据了-----------------------------
    [NetWorkRequest getNetRequestData:GetNearbyStore parmeters:parDic response:^(NSDictionary *response) {
        
        NSDictionary *responseBaseDic = [HelpObject getDocumentDicStrPath:kBasicMessageFilePath];
        
        //        data是一个数组----------------我真是个智障额....
        NSArray *tmpArray = responseBaseDic[@"data"][@"stores"];
        NSArray *tmpTotalStoreArray = tmpArray.firstObject[@"districtlist"];
        //网络数据取出附近门店的数组----然后赋值
        
        weakSelf.totalArray = [NSArray yy_modelArrayWithClass:[TDSearchStoreAreaModel class] json:tmpTotalStoreArray].mutableCopy;
        
        // MARK: - 这个获取的是附近门店的数据--------
        TDSearchStoreAreaModel *nearAreaModel = [TDSearchStoreAreaModel new];
        nearAreaModel.districtnm = @"附近门店";
        nearAreaModel.storelist = [NSArray yy_modelArrayWithClass:[TDSearchStoreModel class] json:response[@"data"][@"storelist"]];
        if (!weakSelf.selLeftIndexPath) {
            nearAreaModel.isSel = YES;
        }
        weakSelf.originNearStoreArray = nearAreaModel.storelist;
        weakSelf.storeDetailArray = nearAreaModel.storelist;
        ////////////////////////////////////////////////
        
        [weakSelf.totalArray insertObject:nearAreaModel atIndex:0];
        
        
        if (weakSelf.selLeftIndexPath) {
            TDSearchStoreAreaModel *model = self.totalArray[weakSelf.selLeftIndexPath.row];
            NSArray *tmpArray = model.storelist;//右侧的了---这个逻辑比车辆简单了很多----
            
            // MARK: - 记录当前的右侧所有门店为纸箱附近门店-------------------------
            weakSelf.storeDetailArray = tmpArray;
            
            model.isSel = YES;
            if (weakSelf.selRightIndexPath) {
                TDSearchStoreModel *tmpStoreModel = tmpArray[weakSelf.selRightIndexPath.row];
                tmpStoreModel.isSel = YES;
            }
        }
      
        [weakSelf.leftTableView reloadData];
        [weakSelf.rightTableView reloadData];
        
        // MARK: - 如果选中了就滚动到指定的位置-------------------
        if (weakSelf.selLeftIndexPath) {
            [weakSelf.leftTableView scrollToRowAtIndexPath:weakSelf.selLeftIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            if (weakSelf.selRightIndexPath) {
                [weakSelf.rightTableView scrollToRowAtIndexPath:weakSelf.selRightIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            }
        }
    } netError:^(NSError *error) {
        
    }];
}

// MARK: - 显示结果按钮点击事件------
- (IBAction)showResultBtnClick:(UIButton *)sender {
    [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelStoreModel = self.selStoreModel;
    if (self.chooseStoreModelBlock) {
        self.chooseStoreModelBlock(_selStoreModel,_selLeftIndexPath,_selRightIndexPath);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)closeBtnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (TDSearchStoreSelModel *)selStoreModel {
    if (!_selStoreModel) {
        _selStoreModel = [[TDSearchStoreSelModel alloc] init];
    }
    return _selStoreModel;
}

- (IBAction)cleanBtnClick:(UIButton *)sender {
    _selStoreModel = [[TDSearchStoreSelModel alloc] init];
    // MARK: - 这个可以用选中的来做   不用循环  后续you'hu
    for (TDSearchStoreAreaModel *model in self.totalArray) {
        model.isSel = NO;
        for (TDSearchStoreModel *tmpStoreModel in model.storelist) {
            tmpStoreModel.isSel = NO;
        }
    }
    TDSearchStoreAreaModel *nearbySroreModel = self.totalArray.firstObject;
    nearbySroreModel.isSel = YES;
    nearbySroreModel.storelist = self.originNearStoreArray;
    [self.leftTableView reloadData];
    [self.rightTableView reloadData];
    [self setDefaultBtnShow];
}





- (void)setBtnShow {
    __weak typeof(self) weakSelf = self;
    _btn_showResult = [[IANActivityIndicatorButton alloc] init];
    _btn_showResult.frame = CGRectMake(0, 5, Width - 40, 40);
    _btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
    _btn_showResult.layer.cornerRadius = 5;
    [_view_showResult addSubview:_btn_showResult];
    [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
    _btn_showResult.TouchBlock = ^(IANActivityIndicatorButton *myButton){
        [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelStoreModel = weakSelf.selStoreModel;
        if (weakSelf.chooseStoreModelBlock) {
            weakSelf.chooseStoreModelBlock(weakSelf.selStoreModel,weakSelf.selLeftIndexPath,weakSelf.selRightIndexPath);
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

- (void)setDefaultBtnShow {
    [_btn_showResult endButtonActivityIndicatorView];
    [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
    _btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
}

- (void)setSelBtnShow {
    [_btn_showResult startButtonActivityIndicatorView];
    [_btn_showResult setTitle:@"加载中" forState:UIControlStateNormal];
}


// MARK: - 获取网络数据-----
- (void)loadAllCarSourceListNetData {
    //    [NetWorkRequest cancel];
    [self setSelBtnShow];
    // MARK: - 获取车源列表--------------
    if (!_locationModel) {
        self.noticeText = @"定位失败,请稍后重试";
        return;
    }
    if ([HelpObject isBlankString:[AppSetting shareAppSetting].topcompanyid]) {
        self.noticeText = @"顶级公司id为空";
        return;
    }
//    self.selStoreModel = [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelStoreModel;
    NSString *topcompanyid = [AppSetting shareAppSetting].topcompanyid;
    NSMutableDictionary *parDic = @{@"topcompanyid":topcompanyid,
                                    @"longitude":_locationModel.longitude,
                                    @"latitude":_locationModel.latitude,
                                    @"prevrows":@"0",
                                    @"showrows":@"1",
                                    }.mutableCopy;
    [self setParaDic:parDic];
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:CarListTD parmeters:parDic response:^(NSDictionary *response) {
        [weakSelf.btn_showResult endButtonActivityIndicatorView];
        weakSelf.btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
        if (response) {
            weakSelf.totalCarNum = [HelpObject changeNull:response[@"data"][@"total"]];
            NSString *tmpStr = [NSString stringWithFormat:@"显示%@车源",weakSelf.totalCarNum];
            [weakSelf.btn_showResult setTitle:tmpStr forState:UIControlStateNormal];
        }else {
        }
    } netError:^(NSError *error) {
        [weakSelf.btn_showResult endButtonActivityIndicatorView];
        weakSelf.btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
    }];
}


- (void)setParaDic:(NSMutableDictionary *)paraDic {
    
    NSString *tmpWorkdayf = [_selDateModel.yearStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    NSString *tmpWorkdayT = [_selDateModel.yearEndStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    
    [paraDic setValue:[HelpObject changeNull:tmpWorkdayf] forKey:@"workdayf"];
    [paraDic setValue:[HelpObject changeNull:tmpWorkdayT] forKey:@"workdayt"];
    [paraDic setValue:[HelpObject changeNull:_selStoreModel.searchStoreModel.storeid] forKey:@"storeid"];
    
    [paraDic setValue:[HelpObject changeNull:_selCarModel.brandid] forKey:@"brandid"];
    
    [paraDic setValue:[HelpObject changeNull:_tf_search_str] forKey:@"cartype"];
    [paraDic setValue:[HelpObject changeNull:_selCarModel.seriesid] forKey:@"seriesid"];
    [paraDic setValue:[TDCarSourceAllMessageModel shareAllMessageModel].orders forKey:@"orders"];
}


@end
